package com.study.a11Test6;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyRunnable implements Runnable{
    Socket socket;
    public MyRunnable(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            //读取数据并保存在本地
            BufferedInputStream bis=new BufferedInputStream(socket.getInputStream());
            //生成文件名
            String name= UUID.randomUUID().toString().replace("-","");
            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("E:\\java-code\\idea-code-study\\mysocketnet\\serverdir\\"+name+".png"));
            byte[] bytes=new byte[1024*1024*5];
            int len;
            while((len=bis.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }


            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("文件上传成功");
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(socket!=null){
                //关闭资源
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
